package de.uni.muenster.idw2.threads;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.util.Log;
import de.uni.muenster.idw2.BuildingChooserMap;
import de.uni.muenster.idw2.data.BoundingBox;
import de.uni.muenster.idw2.xml.BBRequestWriter;
import de.uni.muenster.idw2.xml.BBXMLParser;

public class BBBuildingLoaderThread extends AsyncTask<Void, Void, Void>{
	
	private BuildingChooserMap buildingChooserMap;
	private final BoundingBox bbRequest;

	public BBBuildingLoaderThread(BuildingChooserMap buildingChooserMap, BoundingBox bb){
		this.buildingChooserMap = buildingChooserMap;
		this.bbRequest = bb;
		
	}
	
	@Override
	protected void onPreExecute() {
		buildingChooserMap.showProgress();
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			Log.e("wichtig", e.toString());
		}
		
		
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postMethod = new HttpPost("http://monnti.monnti.bplaced.de/buildings.xml");
			
			ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("bbrequest", BBRequestWriter.getXML(bbRequest)));
			UrlEncodedFormEntity formEntity;
			formEntity = new UrlEncodedFormEntity(postParameters);
			postMethod.setEntity(formEntity);
			
			HttpResponse res = httpClient.execute(postMethod);
			
			BBXMLParser bbxmlParser = new BBXMLParser();
	    	BoundingBox bb = bbxmlParser.getBuildings(res);
	    	if(bb != null){
	    		buildingChooserMap.addOverlayBuildings(bb);
	    	}
			
		} catch (UnsupportedEncodingException e) {
			Log.e("wichtig", e.toString());
		} catch (ClientProtocolException e) {
			Log.e("wichtig", e.toString());
		} catch (IOException e) {
			Log.e("wichtig", e.toString());
		}
		
		
		
    	
		
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		buildingChooserMap.hideProgress();
	}

}
